package com.github.boluo1230.wechat.service.mp.impl;

import com.github.boluo1230.wechat.dao.MpAppDao;
import com.github.boluo1230.wechat.entity.MpApp;
import com.github.boluo1230.wechat.service.mp.MpAppService;
import com.github.boluo1230.wechat.service.mp.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Code Farmer
 * @date 2019/10/14 13:26
 */
@Service
public class MpAppServiceImpl implements MpAppService {

    @Autowired
    private MpAppDao mpAppDao;
    @Autowired
    private RedisService redisService;

    public MpApp findMpApp(String appId) {
        MpApp mpApp = redisService.getCacheMpAppById(appId);
        if (mpApp == null) {
            mpApp = mpAppDao.getMyAppByAppId(appId);
            redisService.setCacheMpAppById(mpApp.getAppId(), mpApp);
        }
        return mpApp;
    }

    @Override
    public List<MpApp> findAll() {
        List<MpApp> mpAppList = redisService.getAllMpApp();
        if (mpAppList == null || mpAppList.size() == 0) {
            mpAppList = mpAppDao.getAll();
            redisService.setAllMpApp(mpAppList);
        }
        return mpAppList;
    }

    @Override
    public long saveMpApp(MpApp mpApp) {
        if (mpApp.getCreateDate() == null) {
            mpApp.setCreateDate(new Date());
        }
        mpApp.setUpdateDate(new Date());
        redisService.delCacheMpAppById(mpApp.getAppId());
        redisService.delAllMpApp();
        return mpAppDao.upsert(mpApp);
    }

}
